package com.example.planstudio;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
//import com.example.myapplication.ListviewAdapt;
//import com.example.myapplication.MsgInfo;


public class MoneyActivity extends AppCompatActivity implements View.OnClickListener {

    private ListviewAdapt adapter = null;

    private ListView listview;
    private Button btn_1;
    private EditText et_meg;
    private TextView role_name;
    private Button btn_2;
    private Button btn_3;
    private Button btn_4;
    private Button btn_5;
    private Button btn_6;
    private Button btn_set;
    private Button btn_statistics;
    private Button btn_update;
    private int type;
    private float money = 0;
    private int ImageId;
    private MyDBhelper myDBhelper;
    private Switch switch1;
    private ImageView tianjia2;
    //    SQLiteDatabase myDatabase;
    private role role2=new role(2131230827,"雪之下由乃");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.moenylayout);
        initView();
//加个传值
//        //导入数据库到创建的文件中
//        MyDatabaseHelper myHelper = new MyDatabaseHelper(MoneyActivity.this);
//        try {
//            myHelper.CopyDBFile();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        String databases_path = getDatabasePath("fund.db").toString();
//        myDatabase = SQLiteDatabase.openDatabase(databases_path, null, SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING);

        adapter = new ListviewAdapt(this);
//        adapter.setServer(2131165294);
        listview.setAdapter(adapter);


    }

    private void initView() {
        listview = (ListView) findViewById(R.id.listview);
        btn_1 = (Button) findViewById(R.id.btn_1);
        et_meg = (EditText) findViewById(R.id.et_meg);
        btn_2 = (Button) findViewById(R.id.btn_2);
        btn_3 = (Button) findViewById(R.id.btn_3);
        btn_4 = (Button) findViewById(R.id.btn_4);
        btn_5 = (Button) findViewById(R.id.btn_5);
        btn_6 = (Button) findViewById(R.id.btn_6);
        tianjia2 = findViewById(R.id.change);
//        btn_set = (Button) findViewById(R.id.btn_set);
        role_name = (TextView) findViewById(R.id.et_input);
//        btn_statistics = (Button) findViewById(R.id.btn_statistics);

        switch1 = findViewById(R.id.switch1);
        tianjia2.setOnClickListener(this);
        btn_1.setOnClickListener(this);
        btn_2.setOnClickListener(this);
        btn_3.setOnClickListener(this);
        btn_4.setOnClickListener(this);
        btn_5.setOnClickListener(this);
        btn_6.setOnClickListener(this);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.print("呜呜呜呜");
        if (requestCode == 0) {
            System.out.print("呜呜呜呜");
            if (resultCode == Activity.RESULT_OK) {
                System.out.print("呜呜呜呜");
//                adapter.notifyDataSetChanged();
//                listview.setAdapter(adapter);
                adapter.clear();
                SharedPreferences preferences = getSharedPreferences("value", 0);
                int name_id = preferences.getInt("value", 0);

                adapter.setServer(name_id);
                myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
//
//                myDBhelper=new MyDBhelper(MoneyActivity.this,"MM.db",null,1);
                List<role> list = new ArrayList<>();

                list = myDBhelper.query2();
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getName_id() == name_id) {
                        role2 = list.get(i);
                    }
                }

                role_name.setText(role2.getName());
//                adapter.setServer_name(role2.getName());
                adapter.notifyDataSetChanged();


//                listview.setAdapter(adapter);
            }
        }

    }

    @SuppressLint("Range")
    @Override
    public void onClick(View v) {

        String msg = et_meg.getText().toString().trim();

        String request = null;
        //new一个角色

        switch (v.getId()) {

            case R.id.change:
                Intent intent = new Intent(MoneyActivity.this, choose_player.class);//SecondActivity为目的Activity
                startActivityForResult(intent, 0);
//
                break;
//            case R.id.btn_statistics:
//                Intent intent1 = new Intent(MoneyActivity.this, pieChartActivity.class);//SecondActivity为目的Activity
//                startActivityForResult(intent1, 0);

//                break;
            case R.id.btn_1:
                if (switch1.isChecked()) {
                    Intent intent2 = new Intent(MoneyActivity.this, SecondActivity.class);
                    intent2.putExtra("msg", "早餐");
                    startActivity(intent2);
                } else {
                    adapter.addDataToAdapter(new MsgInfo(null, "早餐 " + msg));
                    adapter.notifyDataSetChanged();
                    type = 1;
                    try {
                        money = Float.parseFloat(msg);
                    } catch (Exception e) {
                        type = 7;
                    }
                    myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
                    myDBhelper.insert_breakfast(money);
                    request = evaluate_money(type, money);
                    adapter.addDataToAdapter(new MsgInfo(request, null));
                    adapter.notifyDataSetChanged();
                }

                break;
            case R.id.btn_2:
                if (switch1.isChecked()) {
                    Intent intent2 = new Intent(MoneyActivity.this, SecondActivity.class);
                    intent2.putExtra("msg", "正餐");
                    startActivity(intent2);
                } else {
                    adapter.addDataToAdapter(new MsgInfo(null, "中餐 " + msg));
                    adapter.notifyDataSetChanged();
                    type = 2;
                    try {
                        money = Float.parseFloat(msg);
                    } catch (Exception e) {
                        type = 7;
                    }
                    myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
                    myDBhelper.insert_lunch(money);
                    request = evaluate_money(type, money);
                    adapter.addDataToAdapter(new MsgInfo(request, null));
                    adapter.notifyDataSetChanged();
                }

                break;
            case R.id.btn_3:
                if (switch1.isChecked()) {
                    Intent intent1 = new Intent(MoneyActivity.this, pieChartActivity.class);//SecondActivity为目的Activity
                    startActivityForResult(intent1, 0);
//                    Intent intent2 = new Intent(MoneyActivity.this, MyView.class);
//                    intent2.putExtra("msg","学习");
//                    startActivity(intent2);
                } else {
                    adapter.addDataToAdapter(new MsgInfo(null, "晚餐 " + msg));
                    adapter.notifyDataSetChanged();
                    type = 3;
                    try {
                        money = Float.parseFloat(msg);
                    } catch (Exception e) {
                        type = 7;
                    }
                    myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
                    myDBhelper.insert_lunch(money);
                    request = evaluate_money(type, money);
                    adapter.addDataToAdapter(new MsgInfo(request, null));
                    adapter.notifyDataSetChanged();
                }

                break;
            case R.id.btn_4:
                if (switch1.isChecked()) {
                    Intent intent2 = new Intent(MoneyActivity.this, SecondActivity.class);
                    intent2.putExtra("msg", "零食");
                    startActivity(intent2);
                } else {
                    adapter.addDataToAdapter(new MsgInfo(null, "零食 " + msg));
                    adapter.notifyDataSetChanged();
                    type = 4;
                    try {
                        money = Float.parseFloat(msg);
                    } catch (Exception e) {
                        type = 7;
                    }
                    myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
                    myDBhelper.insert_snack(money);
                    request = evaluate_money(type, money);
                    adapter.addDataToAdapter(new MsgInfo(request, null));
                    adapter.notifyDataSetChanged();
                }

                break;
            case R.id.btn_5:
                adapter.addDataToAdapter(new MsgInfo(null, "娱乐 " + msg));
                adapter.notifyDataSetChanged();
                type = 5;
                try {
                    money = Float.parseFloat(msg);
                } catch (Exception e) {
                    type = 7;
                }
                myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
                myDBhelper.insert_amusement(money);
                request = evaluate_money(type, money);
                adapter.addDataToAdapter(new MsgInfo(request, null));
                adapter.notifyDataSetChanged();
                break;
            case R.id.btn_6:
                if (switch1.isChecked()) {
                    Intent intent2 = new Intent(MoneyActivity.this, pieChartActivity.class);
                    startActivity(intent2);
                } else{
                    adapter.addDataToAdapter(new MsgInfo(null, "收入 " + msg));
                    adapter.notifyDataSetChanged();
                    type = 6;
                    try {
                        money = Float.parseFloat(msg);
                    } catch (Exception e) {
                        type = 7;
                    }
//                myDBhelper=new MyDBhelper(MoneyActivity.this,"ffff.db",null,1);
//                myDBhelper.insert_receive(money);
                    request = evaluate_money(type, money);
                    adapter.addDataToAdapter(new MsgInfo(request, null));
                    adapter.notifyDataSetChanged();
                }

                break;
        }


        listview.smoothScrollToPosition(listview.getCount() - 1);

        et_meg.setText("");

    }
    //用来隐藏键盘的
//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//        if (event.getAction() == MotionEvent.ACTION_DOWN) {
//            if (Fragment_Money.this.getCurrentFocus() != null) {
//                if (Fragment_Money.this.getCurrentFocus().getWindowToken() != null) {
//                    imm.hideSoftInputFromWindow(Fragment_Money.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//                }
//            }
//        }
//        return super.onTouchEvent(event);
//    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {

            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            View v = getCurrentFocus();

            if (isShouldHideInput(v, ev)) {
                hideSoftInput(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 隐藏软件盘
     *
     * @param token
     */
    private void hideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private String evaluate_money(int type, double money) {
        //早餐
        if (type == 1) {
            if (money > 0 && money <= 5) {
                myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
                Random random = new Random();
                // 生成随机整数
                int number =random.nextInt(2) + 1;
                return myDBhelper.query3(number, 1, role2.getName_id());
            } else if (money > 5 && money <= 15) {
                myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
                Random random = new Random();
                // 生成随机整数
                int number =   random.nextInt(2) + 4;
                return myDBhelper.query3(number, 1, role2.getName_id());
            } else if (money > 15) {
                myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
                Random random = new Random();
                // 生成随机整数
                int number =random.nextInt(2) + 7;
                return myDBhelper.query3(number, 1, role2.getName_id());
            }

        }
        //中餐，晚餐
        if (type == 2 || type == 3) {
            if (money > 0 && money <= 10) {
                myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
                Random random = new Random();
                // 生成随机整数
                int number = random.nextInt(2) + 1;
                return myDBhelper.query3(number, 2, role2.getName_id());
            } else if (money > 10 && money <= 25) {
                myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
                Random random = new Random();
                // 生成随机整数
                int number = random.nextInt(2) + 4;
                return myDBhelper.query3(number, 2, role2.getName_id());
            } else if (money > 25) {
                myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
                Random random = new Random();
                // 生成随机整数
                int number = random.nextInt(2) + 7;
                return myDBhelper.query3(number, 2, role2.getName_id());
            }

        }

        //零食
        if (type == 4) {
            if (money > 0 && money <= 5) {
                myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
                Random random = new Random();
                // 生成随机整数
                int number = random.nextInt(2) + 1;
                return myDBhelper.query3(number, 3, role2.getName_id());
            } else if (money > 5 && money <= 15) {
                myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
                Random random = new Random();
                // 生成随机整数
                int number = random.nextInt(2) + 4;
                return myDBhelper.query3(number, 3, role2.getName_id());
            } else if (money > 15) {
                myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
                Random random = new Random();
                // 生成随机整数
                int number = random.nextInt(2) + 7;
                return myDBhelper.query3(number, 3, role2.getName_id());
            }

        }
        //娱乐
        if (type == 5) {
            if (money > 0 && money <= 10) {
                myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
                Random random = new Random();
                // 生成随机整数
                int number = random.nextInt(2) + 1;
                return myDBhelper.query3(number, 4, role2.getName_id());
            } else if (money > 10 && money <= 80) {
                myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
                Random random = new Random();
                // 生成随机整数
                int number = random.nextInt(2) + 4;
                return myDBhelper.query3(number, 4, role2.getName_id());
            } else if (money > 80) {
                myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
                Random random = new Random();
                // 生成随机整数
                int number = random.nextInt(2) + 7;
                return myDBhelper.query3(number, 4, role2.getName_id());
            }

        }
        //收入
        if (type == 6) {
            if (money > 0 && money <= 5) {
                myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
                Random random = new Random();
                // 生成随机整数
                int number = random.nextInt(2) + 1;
                return myDBhelper.query3(number, 5, role2.getName_id());
            } else if (money > 5 && money <= 200) {
                myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
                Random random = new Random();
                // 生成随机整数
                int number = random.nextInt(2) + 4;
                return myDBhelper.query3(number, 5, role2.getName_id());
            } else if (money > 200) {
                myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
                Random random = new Random();
                // 生成随机整数
                int number = random.nextInt(2) + 7;
                return myDBhelper.query3(number, 5, role2.getName_id());
            }

        }
        if (type == 7) {

            myDBhelper = new MyDBhelper(MoneyActivity.this, "ffff.db", null, 1);
            Random random = new Random();
            // 生成随机整数
            int number = random.nextInt(2) + 1;
            return myDBhelper.query3(number, 6, role2.getName_id());

        }
        return null;
    }
}
